package com.ledim.service;

import com.ledim.service.coverter.LedimGsonConverterFactory;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by ccx on 16/5/16.
 * 初始化HttpClient以及retrofit--创建各种API service
 */
public class LedimApiServiceFactory {

    private static Retrofit.Builder retrofitBuilder;

    static {
        //if (LogUtil.isDebugChrome()) APIService.httpClientBuilder.addNetworkInterceptor(new StethoInterceptor());
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        if (LogUtil.isDebug) {
            httpClientBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        httpClientBuilder.connectTimeout(30000, TimeUnit.MILLISECONDS);
        httpClientBuilder.readTimeout(30000, TimeUnit.MILLISECONDS);
        httpClientBuilder.writeTimeout(30000, TimeUnit.MILLISECONDS);
        httpClientBuilder.addInterceptor(new HeaderInterceptor());
        httpClientBuilder.retryOnConnectionFailure(true);
        retrofitBuilder =
                new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                                      .addConverterFactory(LedimGsonConverterFactory.create())
                                      .baseUrl(getBaseUrl())
                                      .client(httpClientBuilder.build());
    }

    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = retrofitBuilder.build();
        return retrofit.create(serviceClass);
    }

    public static String getBaseUrl() {
        if (LedimSpUtils.getDebugMark()) {
            return "http://test.api.leciyuan.le.com";
        } else {
            return "http://api.leciyuan.le.com";

        }
    }

    /**
     * 切换Url地址
     */
    public static void resetEnvironment() {
        retrofitBuilder.baseUrl(getBaseUrl());
    }
}
